package org.ayachinene.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;

import java.io.IOException;

public class EmailSender {

    /**
     * 要分割的文件的绝对路径
     */
    public static final String ORIGIN_FILE_PATH = "/Users/ayachinene/Downloads/ideaIC-2022.3.1.exe";

    /**
     * 每份文件大小为20Mb
     */
    public static final int PART_SIZE = 20 * 1024 * 1024;

    /**
     * 发件人邮箱地址
     */
    public static final String SENDER_EMAIL = "123@163.com";

    /**
     * 收件人邮箱地址
     */
    public static final String RECEIVER_EMAIL = "456@163.com";

    /**
     * 所使用的邮件服务地址
     */
    public static final String SMTP_HOST_NAME = "smtp.163.com";

    /**
     * 邮件服务的用户名
     */
    public static final String USERNAME = "123@163.com";

    /**
     * 邮件服务的密码
     */
    public static final String PASSWORD = "password";

    /**
     * 最多可以连续发送多大的文件
     */
    public static final long SEND_SIZE_WITHOUT_STOPPING = Long.MAX_VALUE;

    public static void main(String[] args) throws EmailException, IOException {
        FileSplitter splitter = FileSplitter.filePath(ORIGIN_FILE_PATH)
                .partSize(PART_SIZE)
                .build();
        SplitResult result = splitter.split();

        long curSize = 0;
        for (int i = 0; i < result.fileInfos().size(); ++i) {
            Pair<String, Long> fileInfo = result.fileInfos().get(i);
            String fileName = StringUtils.substringAfterLast(fileInfo.getKey(), "/");
            long fileSize = fileInfo.getValue();

            curSize += fileSize;
            if (curSize >= SEND_SIZE_WITHOUT_STOPPING) {
                System.out.println("已超过可连续发送的最大大小，确保邮箱容量充足后按任意键继续发送");
                @SuppressWarnings("unused") int read = System.in.read();
                System.out.println("继续发送...");
                curSize = fileSize;
            }

            // 发送片段
            EmailAttachment attachment = new EmailAttachment();
            attachment.setPath(fileInfo.getKey());
            attachment.setDisposition(EmailAttachment.ATTACHMENT);
            attachment.setName(fileName);

            MultiPartEmail email = new MultiPartEmail();
            email.setHostName(SMTP_HOST_NAME);
            email.addTo(RECEIVER_EMAIL);
            email.setFrom(SENDER_EMAIL);
            email.setAuthentication(USERNAME, PASSWORD);
            email.setSubject(fileName);
            email.attach(attachment);
            System.out.print("Begin to send " + fileName + ".....   ");
            email.send();
            System.out.println("Done");
        }
    }
}
